;
(function (window, angular) {
    'use strict';
    angular.module("Controller.BasicData.SetPrintTemplate", [])
        .controller("setPrintTemplateCtrl", ["$scope", "$state", "ybWidget", 'ybHttp', 'UserContextService', '$filter', "$timeout", "DEFAULT_TEMPLATE_FUN", function ($scope, $state, ybWidget, ybHttp, UserContextService, $filter, $timeout, DEFAULT_TEMPLATE_FUN) {
            var tempBodyList1 = []; //发运交接单打印模板选择表体的表体1
            var tempBodyList2 = []; //发运交接单打印模板选择表体的表体2
            $scope.printType = "";
            var minPxSafeguard = 10;
            var currentSelectObj = null, currentSelectIndex = -1;
            $scope.checkedList = { //发运交接单打印模板选择表体的默认值
                bodyType: 1
            };
            /*是否是编辑*/
            $scope.isEdit = false;
            /*模板标题样式*/
            $scope.printTempInfo = {};
            /*内容排版*/
            $scope.printTempStyle = {};
            $scope.printTempSelfFoot = {};
            $scope.cacheHeader = [];
            $scope.cacheFoot = [];
            $scope.printTempBd = [];
            $scope.printTempBd2 = [
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "rowNo",
                    Name: "审批人",
                    colWidth: "30%",
                    testValue: "崔雨 40057",
                    widthRate: 2,
                },
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "materialsNo",
                    Name: "用户角色权限",
                    colWidth: "30%",
                    testValue: "职务：服务维修工",
                    widthRate: 2,
                },
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "materialsNo",
                    Name: "审批节点",
                    colWidth: "40%",
                    testValue: "提交单据：2020-05-27 15:07:02",
                    widthRate: 2,
                }
            ];
            $scope.moveBtn = {};
            $scope.titleFontSizeList = [12, 14, 16, 18, 20, 22, 24, 26];
            $scope.bodyFontSizeList = [6, 8, 10, 12, 14, 16, 18];
            /*纸张类型*/
            $scope.pageOrient = {
                lengthwise: 1,
                crosswise: 2
            };

            $scope.previewTableData = [];

            /* wangcan:第二张表，定义表格2模板 */
            $scope.previewTableData2 = [
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "rowNo",
                    Name: "审批人",
                    colWidth: "30%",
                    testValue: "崔雨 40057",
                    widthRate: 2,
                },
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "materialsNo",
                    Name: "用户角色权限",
                    colWidth: "30%",
                    testValue: "职务：服务维修工",
                    widthRate: 2,
                },
                {
                    Alias: "",
                    IsChecked: true,
                    Key: "materialsNo",
                    Name: "审批节点",
                    colWidth: "40%",
                    testValue: "提交单据：2020-05-27 15:07:02",
                    widthRate: 2,
                }
            ];
            var pageEnum = {
                SanLianDan: 1,
                ErLianDan: 2,
                A4: 3,
                CustomPage: 4
            };

            $scope.pageTypes = [
                {
                    Name: "三等分",
                    Value: pageEnum.SanLianDan,
                    Width: 21.59,
                    Height: 9.31,
                    Orient: $scope.pageOrient.lengthwise,
                    Disable: true
                },
                {
                    Name: "二等分",
                    Value: pageEnum.ErLianDan,
                    Width: 21.59,
                    Height: 13.97,
                    Orient: $scope.pageOrient.lengthwise,
                    Disable: true
                },
                {
                    Name: "A4",
                    Value: pageEnum.A4,
                    Width: 21,
                    Height: 29.7,
                    Orient: $scope.pageOrient.lengthwise,
                    Disable: true
                },
                {
                    Name: "自定义",
                    Value: pageEnum.CustomPage,
                    Width: 21.59,
                    Height: 9.31,
                    Orient: $scope.pageOrient.lengthwise,
                    Disable: false
                }
            ];
            $scope.pageMargin = {
                top: 3,
                left: 2,
                right: 2,
                bottom: 1
            };
            $scope.currentPageType = {
                data: []
            };
            $scope.currentPageType.data = $scope.pageTypes[0];
            $scope.previewWin = {
                Width: $scope.currentPageType.data.Width,
                Height: $scope.currentPageType.data.Height
            };

            $scope.$watch("printTempBd", function (newTempalteBody) {
                if (!newTempalteBody || newTempalteBody.length <= 0) {
                    return;
                }
                $scope.previewTableData.length = 0;
                var totalWidthRate = 0;
                angular.forEach(newTempalteBody, function (item) {
                    if (item.IsChecked) {
                        $scope.previewTableData.push(angular.copy(item));
                        totalWidthRate += Number(item.widthRate || 1);
                    }
                });
                angular.forEach($scope.previewTableData, function (item) {
                    item.colWidth = Math.round(Number(item.widthRate || 1) / totalWidthRate * 100) + '%'; //列元素变化重新初始化
                });
            }, true);


            /* ------------wangcan:表格2中表体勾选动作--------------- */
            $scope.$watch("printTempBd2", function (newTempalteBody) {
                if (!newTempalteBody || newTempalteBody.length <= 0) {
                    return;
                }
                /* wangcan:增加表格：表格2模板传值 */
                $scope.previewTableData2.length = 0;
                var totalWidthRate = 0;
                angular.forEach(newTempalteBody, function (item) {
                    if (item.IsChecked) {
                        $scope.previewTableData2.push(angular.copy(item));
                        totalWidthRate += Number(item.widthRate) || 1;
                    }
                });
                angular.forEach($scope.previewTableData2, function (item) {
                    item.colWidth = Math.round((Number(item.widthRate) || 1) / totalWidthRate * 100) + '%'; //列元素变化重新初始化
                });
            }, true);

            $scope.$watch("currentPageType.data", function (pageSize) {
                if (!pageSize) {
                    return;
                }
                if (pageSize.Orient === $scope.pageOrient.lengthwise) {
                    $scope.previewWin.Width = pageSize.Width;
                    $scope.previewWin.Height = pageSize.Height;
                } else {
                    $scope.previewWin.Height = pageSize.Width;
                    $scope.previewWin.Width = pageSize.Height;
                }
            }, true);


            function initGlobalVariable() {
                $scope.printTempInfo = {
                    Id: '',
                    IsDefault: false,
                    TempName: '',
                    TempTitle: {
                        Name: '默认模板',
                        FontSize: $scope.titleFontSizeList[4],
                        nameDescheadFontSize: $scope.titleFontSizeList[2],
                        FontWeight: true,
                        nameDescFontWeight: false,
                    }
                };
                $scope.printTempInfo.TempTitle.Name = window.PrintData[$scope.printType].Name;

                /*内容排版*/
                $scope.printTempStyle = {
                    WordWrap: true, //是否换行
                    FontSize: $scope.bodyFontSizeList[4], //字体大小
                    IsFixedLineNumber: false, //是否启用固定行数
                    FixedLineNumber: 7, //固定行数
                    IsSmallCode: false, //小条码
                    SetHeaderColumn: '2', //表头行列个数
                    SetFootColumn: '2', //表尾行列个数
                    LineHeight: "7", //行高
                    HeadAndFootLineHeight: '6'
                };


                $scope.printTempStyle2 = {
                    WordWrap: true, //是否换行
                    FontSize: $scope.bodyFontSizeList[4], //字体大小
                    IsFixedLineNumber: false, //是否启用固定行数
                    FixedLineNumber: 7, //固定行数
                    IsSmallCode: false, //小条码
                    LineHeight2: "7", //行高
                }

                /*自定义页尾*/
                $scope.printTempSelfFoot = {
                    name: "自定义表尾",
                    value: ""
                };
                $scope.printTempSelfFootShow = '';
                /*表头信息*/
                /*控制弹出框*/
                $scope.IsShowPop = {
                    showTempHeaderPop: false,
                    showTempBdPop1: false,
                    showTempBdPop2: false,
                    showTempFootPop: false
                };

                $scope.moveBtn = {
                    IsSelected: false,
                    canMoveUp: false,
                    canMoveDown: false
                };
                currentSelectObj = null;
                currentSelectIndex = -1;
            }

            function getDefaultTemplateInfo() {
                initTemplateTableHeader();
                initTemplateTableBody();
            }

            var currentTemplate = null;

            function getPrintDataField(dictionTypeName, fieldKeyName) {
                return angular.copy(window.PrintData[$scope.printType][dictionTypeName][fieldKeyName])
            }

            function initTemplateTableHeader() {
                var theaderList = currentTemplate.getTheader();
                $scope.cacheHeader.length = 0;
                $scope.cacheFoot.length = 0;
                angular.forEach(theaderList, function (headerItem) {
                    var temp = getPrintDataField('cacheHeaderFootDiction', headerItem.keyName);
                    if (!temp) {
                        console.error("PrintData:cacheHeaderFootDiction里没有字段：" + headerItem.keyName);
                        return;
                    }
                    temp.Key = headerItem.keyName;
                    temp.IsChecked = headerItem.isChecked;
                    temp.IsHeader = headerItem.isHeader;
                    
                    if (headerItem.isHeader) {
                        $scope.cacheHeader.push(temp);
                    } else {
                        $scope.cacheFoot.push(temp);
                    }
                });
            }

            function initTemplateTableBody() {
                var tbodyCells = currentTemplate.getTbody();
                $scope.printTempBd.length = 0;
                angular.forEach(tbodyCells, function (tbodyItem) {
                    var temp = getPrintDataField('printTempBdDiction', tbodyItem.keyName);
                    if (!temp) {
                        console.error("PrintData:printTempBdDiction里没有字段：" + tbodyItem.keyName);
                        return;
                    }
                    temp.Key = tbodyItem.keyName;
                    temp.IsChecked = tbodyItem.isChecked;
                    
                    if (!!tbodyItem.bodyType) {
                        temp.bodyType = tbodyItem.bodyType;
                    }
                    $scope.printTempBd.push(temp);
                });
                setPrintTempBd();
            }

            function setPrintTempBd(index = 1) {
                if ($scope.printType === "Handover") {
                    tempBodyList1 = $scope.printTempBd.filter(function (item) {
                        return item.bodyType === 1;
                    });
                    tempBodyList2 = $scope.printTempBd.filter(function (item) {
                        return item.bodyType === 2;
                    });
                    $scope.printTempBd = `tempBodyList${index}` === 'tempBodyList1' ? tempBodyList1 : tempBodyList2
                }
            }

            $scope.changeBodyList = function () {
                if ($scope.checkedList.bodyType == 1) {
                    $scope.printTempBd = angular.copy(tempBodyList1);
                }
                if ($scope.checkedList.bodyType == 2) {
                    $scope.printTempBd = angular.copy(tempBodyList2);
                }
            };

            /*设置表头状态*/
            function fnSetHeaderColumns() {
                var cacheList = [],
                    cacheData = {};
                var temp;
                angular.forEach($scope.cacheHeader, function (item) {
                    cacheData.Key = item.Key;
                    cacheData.IsChecked = item.IsChecked;
                    cacheData.IsHeader = item.IsHeader;
                    cacheData.IsAloneRow = item.IsAloneRow;
                    cacheData.Alias = item.Alias;
                    temp = angular.copy(cacheData);
                    cacheList.push(temp);
                });
                return cacheList;
            }

            /*设置表尾状态*/
            function fnSetFootColumns() {
                var cacheList = [],
                    cacheData = {};
                var temp;
                angular.forEach($scope.cacheFoot, function (item) {
                    cacheData.Key = item.Key;
                    cacheData.IsChecked = item.IsChecked;
                    cacheData.IsHeader = item.IsHeader;
                    cacheData.IsAloneRow = item.IsAloneRow;
                    cacheData.Alias = item.Alias;
                    temp = angular.copy(cacheData);
                    cacheList.push(temp);
                });
                return cacheList;
            }

            /*拼接表头表尾*/
            function getHeaderFooterColumnInfo() {
                var HeaderFooterColumnInfo = {};
                HeaderFooterColumnInfo.cahcheHeaderList = fnSetHeaderColumns();
                HeaderFooterColumnInfo.cahcheFootList = fnSetFootColumns();

                HeaderFooterColumnInfo.alwaysShowHeadFoot = $scope.printTempStyle.SetAlwaysShowHeadFoot;

                return HeaderFooterColumnInfo;
            }

            /*设置表体状态 new*/
            function getTbodyInfo() {
                var cacheList = [],
                    cacheData = {},
                    temp;
                var printTempBd = angular.copy($scope.printTempBd);
                angular.forEach(printTempBd, function (item) {
                    cacheData = {};
                    if (item.IsChecked) {
                        angular.forEach($scope.previewTableData, function (table, index) {
                            if (table.Key === item.Key) {
                                item.colWidth = table.colWidth;
                            }
                        });
                        cacheData.colWidth = item.colWidth;
                    }
                    if (!!item.bodyType) {
                        cacheData.bodyType = item.bodyType;
                    }
                    cacheData.Key = item.Key;
                    cacheData.IsChecked = item.IsChecked;
                    cacheData.Alias = item.Alias;
                    cacheData.widthRate = item.widthRate; // 记录用户设置的列宽度比重
                    temp = angular.copy(cacheData);
                    cacheList.push(temp);
                });
                return cacheList;
            }

            //获取模板详情
            function getTemplateInfo(templateId) {
                ybHttp.Get("device", "/printTemplate/item", {
                    id: templateId
                }).then(function (data) {
                    if (data.code !== 0) {
                        ybWidget.ShowMessage(data);
                        return;
                    }
                    $scope.printTempInfo.Id = data.value.id;
                    $scope.printTempInfo.TempName = data.value.templateName;

                    $scope.printTempInfo.TempTitle.Name = data.value.headMessage;
                    $scope.printTempInfo.TempTitle.FontSize = data.value.headFontSize;
                    if (angular.isDefined(data.value.isHeadlineFontBold)) {
                        $scope.printTempInfo.TempTitle.FontWeight = data.value.isHeadlineFontBold;
                    }
                    if (angular.isDefined(data.value.isNameDescFontBold)) {
                        $scope.printTempInfo.TempTitle.nameDescFontWeight = data.value.isNameDescFontBold;
                        // 增加标题描述字体是否加粗
                    }
                    $scope.printTempInfo.TempTitle.NameDesc = data.value.headDesc; // 增加标题描述
                    $scope.printTempInfo.TempTitle.nameDescheadFontSize = data.value.nameDescheadFontSize;// 增加标题描述字体大小
                    
                    if (data.value.bottomMessage) {
                        var reg = new RegExp("<br/>", "g"); //创建正则RegExp对象
                        $scope.printTempSelfFoot.value = data.value.bottomMessage.replace(reg, '\n');
                        var regExp = new RegExp("  ", "g"); //创建正则RegExp对象
                        $scope.printTempSelfFootShow = data.value.bottomMessage.replace(regExp, '&emsp;');
                    }
                    $scope.printTempInfo.IsDefault = data.value.isDefault;
                    $scope.printTempStyle.IsSmallCode = data.value.isPrintMinCode;
                    $scope.printTempStyle.IsSubtotal = data.value.isPrintPageSubtotal;
                    $scope.printTempStyle.IsFixedLineNumber = data.value.isPrintLine;
                    $scope.printTempStyle.LineHeight = data.value.lineHeight != '0' ? data.value.lineHeight : $scope.printTempStyle.lineHeight;
                    var pageSetting = angular.fromJson(data.value.pageSetting); //打印配置对象
                    var contentSetting = angular.fromJson(data.value.contentSetting);
                    if (!!contentSetting) {
                        $scope.printTempStyle.IsPrintHead = contentSetting.isPrintHead;
                        $scope.printTempStyle.IsPrintFoot = contentSetting.isPrintFoot;
                        $scope.printTempStyle.HeadAndFootLineHeight = contentSetting.HeadAndFootLineHeight || $scope.printTempStyle.HeadAndFootLineHeight;
                    }
                    if (!!data.value.isPrintLine) {
                        $scope.printTempStyle.FixedLineNumber = data.value.printLineNum;
                    }
                    if (angular.isDefined(data.value.isBodyAutoLineWrap)) {
                        $scope.printTempStyle.WordWrap = data.value.isBodyAutoLineWrap;
                    }
                    if (data.value.bodyFontSize) {
                        $scope.printTempStyle.FontSize = data.value.bodyFontSize;
                    }
                    if (data.value.headerColumnNum) {
                        $scope.printTempStyle.SetHeaderColumn = data.value.headerColumnNum;
                    }
                    if (data.value.footerColumnNum) {
                        $scope.printTempStyle.SetFootColumn = data.value.footerColumnNum;
                    }

                    setHeaderFooterColumnInfo(data.value.headerFooterColumnInfo);
                    setBodyColumnInfo(data.value.bodyColumnInfo);
                    setCurrentPageType(pageSetting);
                    $scope.fixedProductsLine();
                    $timeout(function () {
                        initTableDataWhenEdit($scope.printTempBd);
                    }, 10);
                });
            }

            function setHeaderFooterColumnInfo(headerFooterColumnInfo) {
                if (!headerFooterColumnInfo) {
                    return;
                }
                var columnInfo = angular.fromJson(headerFooterColumnInfo);

                $scope.printTempStyle.SetAlwaysShowHeadFoot = columnInfo.alwaysShowHeadFoot || false;

                $scope.cacheHeader.length = 0;
                $scope.cacheFoot.length = 0;
                const createdTempFieldArr = columnInfo.cahcheHeaderList.concat(columnInfo.cahcheFootList);
                for(let headerItem of createdTempFieldArr) {
                    var temp = getPrintDataField('cacheHeaderFootDiction', headerItem.Key);
                    if (!temp) continue;

                    temp.Key = headerItem.Key;
                    temp.IsChecked = headerItem.IsChecked;
                    temp.IsHeader = headerItem.IsHeader;
                    temp.IsAloneRow = headerItem.IsAloneRow;
                    temp.Alias = headerItem.Alias;
                    if (headerItem.IsHeader) {
                        $scope.cacheHeader.push(temp);
                    } else {
                        $scope.cacheFoot.push(temp);
                    }
                }

                handleAddedHeaderFooterFieldsAfterTemplateCreated(createdTempFieldArr);
            }

            function handleAddedHeaderFooterFieldsAfterTemplateCreated(createdTempFields) {
                // 模板建好后，需求又新增的字段
                const theaderList = currentTemplate.getTheader();
                const additionHeaderFooters = theaderList.filter(th => !createdTempFields.find(cf => cf.Key == th.keyName));
                for(let newItem of additionHeaderFooters) {
                    var temp = getPrintDataField('cacheHeaderFootDiction', newItem.keyName);
                    if (!temp) continue;

                    temp.Key = newItem.keyName;
                    temp.IsHeader = newItem.isHeader;
                    temp.IsChecked = false;
                    if (newItem.isHeader) {
                        $scope.cacheHeader.push(temp);
                    } else {
                        $scope.cacheFoot.push(temp);
                    }
                }
            }

            function setBodyColumnInfo(bodyColumnInfo) {
                if (!bodyColumnInfo) {
                    return;
                }

                var bodyColumnList = angular.fromJson(bodyColumnInfo);
                var templateBody = [];

                for (var i = 0; i < bodyColumnList.length; i++) {
                    var tbodyItem = bodyColumnList[i];
                    var temp = getPrintDataField('printTempBdDiction', tbodyItem.Key);
                    if (!temp) continue;

                    temp.Key = tbodyItem.Key;
                    temp.IsChecked = tbodyItem.IsChecked;
                    temp.Alias = tbodyItem.Alias;
                    temp.widthRate = tbodyItem.widthRate; // 取出保存的列宽度比重
                    if (angular.isDefined(tbodyItem.colWidth)) {
                        temp.colWidth = tbodyItem.colWidth;
                    }
                    if (!!tbodyItem.bodyType) {
                        temp.bodyType = tbodyItem.bodyType;
                    }

                    templateBody.push(temp);
                }

                if (!!bodyColumnList[0] && !!bodyColumnList[0].bodyType) {
                    $scope.checkedList.bodyType = bodyColumnList[0].bodyType;
                }

                handleAddedBodyFieldsAfterTemplateCreated(bodyColumnList, templateBody);

                $scope.printTempBd = templateBody;
                if ($scope.printType === "Handover") {
                    // 发运交接单处理 装箱前、装箱后的表体字段
                    // 因为每次的打印模板只会是一种装箱类型（装箱前or装箱后），所以 需要把非本次装箱类型的 数据来源 同新增一样处理好
                    setPrintTempBd($scope.checkedList.bodyType);
                }
            }

            function handleAddedBodyFieldsAfterTemplateCreated(createdTempFields, newTemplateBody) {
                // 模板建好后，需求又新增的字段
                const tbodyCells = currentTemplate.getTbody();
                // TODO
                // 遗留一个问题，发运交接单装箱前or装箱后的已建模板假如选择了序号（装箱前、装箱后序号keyName相同，类型不同）,会展示异常
                const additionBodys = tbodyCells.filter(th => !createdTempFields.find(cf => cf.Key == th.keyName));
                for(let newItem of additionBodys) {
                    var temp = getPrintDataField('printTempBdDiction', newItem.keyName);
                    if (!temp) continue;

                    temp.Key = newItem.keyName;
                    temp.IsChecked = false;
                    if (!!newItem.bodyType) {
                        temp.bodyType = newItem.bodyType;
                    }

                    newTemplateBody.push(temp);
                }
            }

            function initTableDataWhenEdit(newTempalteBody) {
                var cleanPreviewTableData = true;
                angular.forEach(newTempalteBody, function (item) {
                    if (item.IsChecked && !!item.colWidth) {
                        if (cleanPreviewTableData) {
                            $scope.previewTableData.length = 0;
                            cleanPreviewTableData = false;
                        }
                        $scope.previewTableData.push(angular.copy(item));
                    }
                });
            }

            function setCurrentPageType(pageSetting) {
                if (!pageSetting) {
                    return $scope.currentPageType.data = $scope.pageTypes[0];
                }
                if (!!pageSetting.pageMargin) {
                    $scope.pageMargin = angular.copy(pageSetting.pageMargin);
                }
                for (var i = 0; i < $scope.pageTypes.length; i++) {
                    var item = $scope.pageTypes[i];
                    if (pageSetting.Value === item.Value) {
                        $scope.currentPageType.data = item;
                        item.Orient = pageSetting.Orient;
                        if (pageEnum.CustomPage === item.Value) {
                            item.Width = pageSetting.Width;
                            item.Height = pageSetting.Height;
                        }
                        return;
                    }
                }
            }

            //保存打印模板
            $scope.savePrintTemplate = function () {
                if (!$scope.printTempInfo.TempTitle.Name || !$scope.printTempInfo.TempName || !$scope.printTempStyle.LineHeight || !$scope.printTempStyle.HeadAndFootLineHeight) {
                    ybWidget.ShowMessage("缺少必填信息");
                    return;
                }
                var setHeaderFootColumns = getHeaderFooterColumnInfo();
                var paramHeaderCounts = calcuHeadOrFootCounts('#calcu-select-head-height');
                var paramFootCounts = calcuHeadOrFootCounts('#calcu-select-tfoot-height');
                var paramCustomFootCounts = calcuHeadOrFootCounts('#calcu-custom-foot-height');
                var paramTotalFootCounts = Number(ybWidget.Plus(paramFootCounts, paramCustomFootCounts));
                var contentSetting = {
                    tHeadCounts: paramHeaderCounts,
                    tFootCounts: paramTotalFootCounts,
                    isPrintHead: $scope.printTempStyle.IsPrintHead,
                    isPrintFoot: $scope.printTempStyle.IsPrintFoot,
                    HeadAndFootLineHeight: $scope.printTempStyle.HeadAndFootLineHeight
                };
                var bodyColumnInfo = getTbodyInfo();
                var bottomMessage = $scope.printTempSelfFoot.value;
                var reg = new RegExp("\n", "g"); //创建正则RegExp对象
                bottomMessage = bottomMessage.replace(reg, '<br/>');
                var pageSetting = angular.copy($scope.currentPageType.data);
                pageSetting.pageMargin = $scope.pageMargin;
                var param = {
                    headMessage: $scope.printTempInfo.TempTitle.Name,
                    headFontSize: $scope.printTempInfo.TempTitle.FontSize,
                    isHeadlineFontBold: $scope.printTempInfo.TempTitle.FontWeight,
                    headDesc: $scope.printTempInfo.TempTitle.NameDesc, // 增加标题描述
                    nameDescheadFontSize: $scope.printTempInfo.TempTitle.nameDescheadFontSize,// 增加标题描述字体大小
                    isNameDescFontBold: $scope.printTempInfo.TempTitle.nameDescFontWeight,// 增加标题描述是否加粗
                    templateName: $scope.printTempInfo.TempName,
                    templateType: $state.params.templateTypeCode,
                    isDefault: $scope.printTempInfo.IsDefault,
                    bottomMessage: bottomMessage,
                    isPrintLine: $scope.printTempStyle.IsFixedLineNumber,
                    isPrintMinCode: $scope.printTempStyle.IsSmallCode,
                    isPrintPageSubtotal: $scope.printTempStyle.IsSubtotal,
                    printLineNum: parseInt($scope.printTempStyle.FixedLineNumber),
                    isBodyAutoLineWrap: $scope.printTempStyle.WordWrap,
                    bodyFontSize: $scope.printTempStyle.FontSize,
                    headerColumnNum: $scope.printTempStyle.SetHeaderColumn,
                    footerColumnNum: $scope.printTempStyle.SetFootColumn,
                    headerFooterColumnInfo: angular.toJson(setHeaderFootColumns),
                    bodyColumnInfo: angular.toJson(bodyColumnInfo),
                    pageSetting: angular.toJson(pageSetting),
                    lineHeight: $scope.printTempStyle.LineHeight,
                    contentSetting: angular.toJson(contentSetting)
                };
                var reqUrl = "";
                if (!$scope.isEdit) {
                    reqUrl = "/printTemplate/insert";
                    param.IsDel = false;
                } else {
                    reqUrl = "/printTemplate/update";
                    param.id = $scope.printTempInfo.Id;
                }
                ybHttp.Post('device', reqUrl, param).then(function (data) {
                    if (data.code !== 0) {
                        ybWidget.ShowMessage(data);
                        return;
                    }
                    ybWidget.ShowToaster("success", "操作提示", "操作成功");
                    $scope.$emit('updateTemplateList');
                    ybWidget.GoBack();
                });
            };

            function calcuHeadOrFootCounts(headOrFootId) {
                if (!$scope.printTempStyle.IsFixedLineNumber) {
                    return 0;
                }
                if (!document.querySelector(headOrFootId)) {
                    return 0;
                }
                var headOrFootHeight = document.querySelector(headOrFootId).offsetHeight;
                var lineHeightToPx = $filter('convertMMToPx')($scope.printTempStyle.LineHeight);
                if (headOrFootHeight < minPxSafeguard) {
                    return 0;
                }
                if (lineHeightToPx <= 0) {
                    lineHeightToPx = 1;
                }
                return Math.floor(ybWidget.Divide(headOrFootHeight, lineHeightToPx));
            }

            //打印单据固定商品行数展示
            $scope.fixedProductsLine = function () {
                $scope.setFixedLineFlag();
                if ($scope.printTempStyle.IsFixedLineNumber) {
                    //存储填充空行
                    $scope.FixedLine = [];
                    var productLen = 1;
                    var lineLen = $scope.printTempStyle.FixedLineNumber || 7;
                    var len = 0;
                    if ($scope.printTempStyle.IsSubtotal) {
                        len = (lineLen - (productLen + 2) % lineLen) % lineLen;
                    } else {
                        len = (lineLen - (productLen + 1) % lineLen) % lineLen;
                    }
                    $scope.FixedLine.length = len;
                } else {
                    $scope.FixedLine = [];
                }
            };

            $scope.$watch('printTempStyle.IsFixedLineNumber', function () {
                $scope.fixedProductsLine();
            });

            $scope.setFixedLineFlag = function () {
                if ($scope.printTempStyle.IsSubtotal && $scope.printTempStyle.IsPrintFoot) {
                    $scope.printTempStyle.IsFixedLineNumber = true;
                }
            };

            /*取消*/
            $scope.goback = function () {
                ybWidget.GoBack();
            };

            /*表头弹窗*/
            $scope.setPrintHeaderPop = function () {
                $scope.IsShowPop.showTempHeaderPop = !$scope.IsShowPop.showTempHeaderPop;
            };
            /*表体设置弹窗*/
            $scope.setPrintBdPop1 = function () {
                $scope.IsShowPop.showTempBdPop1 = !$scope.IsShowPop.showTempBdPop1;
            };
            $scope.setPrintBdPop2 = function () {
                $scope.IsShowPop.showTempBdPop2 = !$scope.IsShowPop.showTempBdPop2;
            };
            /*表尾弹窗*/
            $scope.setPrintFootPop = function () {
                $scope.IsShowPop.showTempFootPop = !$scope.IsShowPop.showTempFootPop;
            };
            /*移至表尾*/
            $scope.fnMoveToFoot = function (obj, index) {
                obj[index].IsHeader = 0;
                $scope.cacheFoot.push(obj.splice(index, 1)[0]);
            };
            /*移至表头*/
            $scope.fnMoveToHeader = function (obj, index) {
                obj[index].IsHeader = 1;
                $scope.cacheHeader.push(obj.splice(index, 1)[0]);
            };

            /*关闭弹窗*/
            $scope.closePop = function () {
                $scope.IsShowPop = {
                    showTempHeaderPop: false,
                    showTempBdPop1: false,
                    showTempBdPop2: false,
                    showTempFootPop: false
                };
                $scope.moveBtn = {
                    IsSelected: false,
                    canMoveUp: false,
                    canMoveDown: false
                };
                currentSelectObj = null;
                currentSelectIndex = -1;
                angular.forEach($scope.cacheHeader, function (item) {
                    item.IsSelected = false;
                });
                angular.forEach($scope.printTempBd, function (item) {
                    item.IsSelected = false;
                });
                angular.forEach($scope.cacheFoot, function (item) {
                    item.IsSelected = false;
                });

            };
            /*设置选中时按钮状态*/
            $scope.setSelectStyle = function (obj, index) {
                index === 0 ? $scope.moveBtn.canMoveUp = false : $scope.moveBtn.canMoveUp = true;
                index === (obj.length - 1) ? $scope.moveBtn.canMoveDown = false : $scope.moveBtn.canMoveDown = true;
                if (currentSelectIndex >= 0) {
                    currentSelectObj[currentSelectIndex].IsSelected = false;
                }
                obj[index].IsSelected = true;
                currentSelectObj = obj;
                currentSelectIndex = index;
                $scope.moveBtn.IsSelected = true;

            };

            $scope.fnMoveUp = function () {
                var obj = currentSelectObj;
                var index = currentSelectIndex;
                if (obj === null && index === -1) {
                    $scope.moveBtn.canMoveDown = false;
                    $scope.moveBtn.canMoveUp = false;
                    return;
                }
                if (currentSelectIndex > 0) {
                    currentSelectIndex--;
                    $scope.moveBtn.canMoveDown = true;
                    if (!currentSelectIndex) {
                        $scope.moveBtn.canMoveUp = false;
                    } else {
                        $scope.moveBtn.canMoveUp = true;
                    }
                }
                var temp = obj[index];
                obj[index] = obj[index - 1];
                obj[index - 1] = temp;
            };
            $scope.fnMoveDown = function () {
                var obj = currentSelectObj;
                var index = currentSelectIndex;
                if (obj === null && index === null) {
                    $scope.moveBtn.canMoveDown = false;
                    $scope.moveBtn.canMoveUp = false;
                    return;
                }
                if (currentSelectIndex < currentSelectObj.length - 1) {
                    currentSelectIndex++;
                    $scope.moveBtn.canMoveUp = true;
                    if (currentSelectIndex = currentSelectObj.length - 1) {
                        $scope.moveBtn.canMoveDown = false;
                    } else {
                        $scope.moveBtn.canMoveDown = true;
                    }
                }
                var temp = obj[index];
                obj[index] = obj[index + 1];
                obj[index + 1] = temp;
            };

            /*自定义表尾展示*/
            $scope.changeprintTempSelfFootShow = function (str) {
                var bottomMessage = str;
                var reg = new RegExp("\n", "g"); //创建正则RegExp对象
                bottomMessage = bottomMessage.replace(reg, '<br/>');
                var regExp = new RegExp("  ", "g"); //创建正则RegExp对象
                $scope.printTempSelfFootShow = bottomMessage.replace(regExp, '&emsp;');
            };

            //模板预览
            $scope.previewOnPrinter = async function () {
                var lodop = UserContextService.GetLodop();
                if (!lodop) {
                    return;
                }
                
                if (!await UserContextService.InitPrinter(lodop)) {
                    return;
                }

                lodop.SET_PRINT_PAGESIZE($scope.currentPageType.data.Orient, $scope.currentPageType.data.Width + 'cm', $scope.currentPageType.data.Height + 'cm', "");
                lodop.SET_PRINT_MODE("RESELECT_PRINTER", true);
                lodop.SET_PRINT_MODE("RESELECT_ORIENT", true);
                lodop.SET_PRINT_MODE("RESELECT_PAGESIZE", true);
                var topMargin = ($scope.pageMargin.top || 0) + "mm";
                var leftMargin = ($scope.pageMargin.left || 0) + "mm";
                var rightMargin = "RightMargin:" + ($scope.pageMargin.right || 0) + "mm";
                var bottomMargin = "BottomMargin:" + ($scope.pageMargin.bottom || 0) + "mm";
                lodop.ADD_PRINT_TABLE(topMargin, leftMargin, rightMargin, bottomMargin, document.getElementsByClassName('print-item')[0].innerHTML); // 增加表格打印项 上左右下边距
                lodop.PREVIEW();
            };

            $scope.setTableHeaderItemWidth = function (isAloneRow) {
                return getTableItemWidth(isAloneRow, $scope.printTempStyle.SetHeaderColumn);
            };
            $scope.setTableFooterItemWidth = function (isAloneRow) {
                return getTableItemWidth(isAloneRow, $scope.printTempStyle.SetFootColumn);
            };

            function getTableItemWidth(isAloneRow, columns) {
                var result = {
                    width: "99.99999%",
                    float: 'left'
                };
                if (isAloneRow) {
                    return result;
                }
                result.width = 99 / parseInt(columns) + "%";
                return result;
            }

            ybWidget.SetParentMainView($scope);

            (function () {
                $scope.printType = $state.params.printType || "";
                currentTemplate = DEFAULT_TEMPLATE_FUN($scope.printType);
                if (!currentTemplate) {
                    return;
                }
                initGlobalVariable();
                if ($state.params.id) {
                    getTemplateInfo($state.params.id); //编辑订单
                    $scope.isEdit = true;
                } else {
                    getDefaultTemplateInfo();
                }
            })();
        }])
})(window, window.angular);
